package cn.lichenes.controller;

import cn.lichenes.entity.Phone;
import cn.lichenes.entity.PhonePicture;
import cn.lichenes.log.SystemLog;
import cn.lichenes.service.PhoneService;
import cn.lichenes.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PhoneController {

    @Autowired
    private PhoneService phoneService;
    @Value("${spring.servlet.multipart.location}")
    private String FILE_UPLOAD_PATH;

    @GetMapping("/management-phones")
    public String managementPhones(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                   @RequestParam(value = "keyword",defaultValue = "") String keyword,
                                   Model model){
        Map<String, Object> map = phoneService.findAll(page,keyword);
        map.put("keyword",keyword);
        model.addAllAttributes(map);
        return "management-phones";
    }

    @GetMapping("/phones")
    public String Phones(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                   @RequestParam(value = "keyword",defaultValue = "") String keyword,
                                   Model model){
        Map<String, Object> map = phoneService.findAll(page,keyword);
        map.put("keyword",keyword);
        model.addAllAttributes(map);
        return "management-phones::phones";
    }

    @SystemLog(value = "修改手机信息",status = "admin")
    @PutMapping("/management-phones/{id}")
    public String updatePhone(@PathVariable("id")Integer id, double price, Integer residue, String description,String status){
        boolean flag = phoneService.updatePhone(id,price,residue,description,status);
        return "redirect:/management-phones";
    }

    @SystemLog(value = "上架新手机",status = "admin")
    @PostMapping("/management-phones")
    public String addPhone(HttpServletRequest request,@RequestParam(value = "file") MultipartFile[] files, String name, String brand, double price, Integer residue, String description){
        System.out.println(name+","+brand+","+price+","+residue+","+description);
        System.out.println( files.length);
        try {
            List<PhonePicture> pictures = new ArrayList<>();
            PhonePicture phonePicture = null;
            String uuid = Utils.getUUID();
            Phone phone = new Phone();
            phone.setpName(name);
            phone.setpPrice(price);
            phone.setpResidue(residue);
            phone.setpDescription(description);
            phone.setpStatus(1);
            phone.setpSales(0);
            phone.setpUuid(uuid);
            for (MultipartFile file : files) {
                phonePicture = new PhonePicture();
                uuid = Utils.getUUID();
                String originalFilename = file.getOriginalFilename();
                String extendName = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
                String fileName = uuid + extendName;
                File dir = new File(FILE_UPLOAD_PATH, fileName);
                file.transferTo(dir);
                phonePicture.setPicName(uuid);
                phonePicture.setPicAddress("/file/"+fileName);
                pictures.add(phonePicture);
            }
           boolean flag =  phoneService.save(phone,brand,pictures);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/management-phones";
    }

    @GetMapping(value = {"/shopIndex","/"})
    public String shopIndex(Model model){
        Map<String, Object> map = phoneService.getAll();
        model.addAllAttributes(map);
        return "shopIndex";
    }

    @GetMapping(value = {"/shopAll","/shopAll/{brand}","/shopAll/{brand}/{price}"})
    public String shopAll(@PathVariable(value = "brand",required = false) String brand,
                          @PathVariable(value = "price",required = false) Double price,
                          @RequestParam(value = "page",defaultValue = "1") Integer page,
                          Model model){
        System.out.println(brand+","+price);
        if ("all".equals(brand)) {
            brand = null;
        }
        Page<Phone> phonePage = phoneService.getPhoneByPrice(brand, price, page);
        Map<String,Object> map = new HashMap<>();
        map.put("phones",phonePage.getContent());
        map.put("currentPage",page);
        map.put("totalPages",phonePage.getTotalPages());
        map.put("brand",brand);
        map.put("price",price);
        model.addAllAttributes(map);
        return "shopAll";
    }

    @GetMapping(value = {"/singleShop/{id}","/singleShop/{id}/{oid}"})
    public String singleShop(@PathVariable(value = "id")Integer id, @PathVariable(value = "oid",required = false)Integer oid, Model model){
        Map<String, Object> map = phoneService.getPhoneById(id);
        map.put("indent",oid);
        model.addAllAttributes(map);
        return "singleShop";
    }
}
